package com.sciai.Service.impl;

import cn.com.sciai.aix.common.http.SciaiHttpResponseEntity;
import cn.com.sciai.aix.common.http.SciaiHttpResponseEntityBuilder;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csvreader.CsvReader;
import com.sciai.Service.CsvDataService;
import com.sciai.Service.TBusinessService;
import com.sciai.entity.CsvData;
import com.sciai.entity.Weather;
import com.sciai.entity.WeatherType;
import com.sciai.mapper.CsvDataMapper;
import com.sciai.mapper.WeatherMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 文件 服务实现类
 * </p>
 *
 * @author tqx
 * @since 2023-09-26
 */
@Service
@Slf4j
public class CsvDataServiceImpl extends ServiceImpl<CsvDataMapper, CsvData> implements CsvDataService {
    @Resource
    private WeatherMapper WeatherMapper;
    @Resource
    private TBusinessService tBusinessService;
    @Override
    public SciaiHttpResponseEntity CSVImport(String filePath) {

        //接收返回的数据返回给前端
        CsvData csvData =null;
        CsvReader r;
        try{
            // 获取当前日期和时间
            Calendar calendar = Calendar.getInstance();
            // 将日期减去一天
            calendar.add(Calendar.DAY_OF_MONTH, 0);
            // 格式化日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String previousDay = dateFormat.format(calendar.getTime());
            //放文件的位置
//            String cvsFilePath="D:\\"+previousDay+"\\"+filePath;  //本地开发
            log.info("开始file2");
            String cvsFilePath="/opt/project/file/import/"+previousDay+"/"+filePath;  //服务器开发
            log.info("结束file2");
            r = new CsvReader(cvsFilePath,',', Charset.forName("utf-8"));
            //读取表头
            boolean b = r.readHeaders();
            List<CsvData> list = new LinkedList<CsvData>();
            List<Weather> list2 = new LinkedList<Weather>();
            int row =1;
            //先查询天气类型
            //查询天气类型
            Map<String, Object> params = new HashMap<>();
            List<WeatherType> weatherTypes = WeatherMapper.queryWeatherType(params);
            if (weatherTypes.size()==0){
                return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
            }
            List<String> wbIdList= new ArrayList<>();
            List<String> occurrenceTimeList= new ArrayList<>();
            while(r.readRecord()){
                csvData = new CsvData();
                Weather weather =new Weather();
                weather.setType(2);
                //注意，此处的id,name,school是csv文件里的列名
                String s = r.get("页码");
                String[] strings =  r.getValues();
                int a = Integer.parseInt(strings[0]);
                csvData.setPageNum(a);
                csvData.setWbId(strings[1].substring(1));
                csvData.setWbName(strings[2]);
                weather.setName(strings[2]);
                String dateString = strings[3].replace("/","-");
                int q = dateString.indexOf(" ");
                String str1 =dateString.substring(q);
                List<String> list1 = Arrays.asList(str1.split(":"));
                if (list1.size()==2){
                    dateString=dateString+":00";
                }

//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date1 = DateUtil.parse(dateString, "yyyy-MM-dd HH:mm:ss");
//                Date date = format.parse(dateString);
                csvData.setOccurrenceTime(date1);
                weather.setOccurrenceTime(date1);
                csvData.setContent(strings[4]);
                weather.setDescribeName(strings[4]);
                int a1 = Integer.parseInt(strings[5]);
                csvData.setForwardNum(a1);
                int a2 = Integer.parseInt(strings[6]);
                csvData.setCommentNum(a2);
                int a3 = Integer.parseInt(strings[7]);
                csvData.setLikeNum(a3);
                csvData.setOccurrencePlace(strings[8].equals("")? "":strings[8]);
                csvData.setOccurrenceCity(strings[9].equals("")? "":strings[9]);
                csvData.setOccurrenceProvince(strings[10].equals("")? "":strings[10]);
                weather.setOccurrencePlace(strings[10].equals("")? "":strings[10]);
                csvData.setOccurrenceCountry(strings[11].equals("")? "":strings[11]);
                if (!strings[12].equals("999") && !strings[12].equals("999.0") && !strings[12].equals("999.00")){
                    csvData.setLon(strings[12]);
                    weather.setOccurrencePlace1(strings[12]);
                    csvData.setLat(strings[13]);
                    weather.setOccurrencePlace2(strings[13]);
                    weather.setVideoUuid("");
                    weather.setImagUuid("");
                    weather.setCreateUserId(1);
                    weather.setCreateTime(new Date());
                    boolean f=false; //判断是否在系统的基础数据里 天气类型
                    if (strings[14].equals("")||strings[14].equals("null")||strings[14]==null){
                        return SciaiHttpResponseEntityBuilder.builder().error("500", "第"+row+"行的天气类型不能为空！").build();
                    }else {
                        for (int i=0; i<weatherTypes.size();i++){
                            if (weatherTypes.get(i).getTypeName().equals(strings[14])){
                                csvData.setWeatherType(weatherTypes.get(i).getId());
                                weather.setWeatherType(weatherTypes.get(i).getId());
                                weather.setWeatherTypeName(strings[14]);
                                f=true;
                                break;
                            }
                        }
                    }
                    if (!f){
                        //不在
                        return SciaiHttpResponseEntityBuilder.builder().error("500", "第"+row+"行的天气类型不在基础数据里！").build();
                    }
                    csvData.setCreateTime(new Date());
                    row=row+1;
                    list.add(csvData);
                    wbIdList.add(csvData.getWbId());
                    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String occurrenceTime = dateFormat2.format(csvData.getOccurrenceTime());
                    occurrenceTimeList.add(occurrenceTime);
                    list2.add(weather);
                }
            }
            List<CsvData> csvDataList = new ArrayList<>();
            if (wbIdList.size()>0){
                Map<String, Object> params2 = new HashMap<>();
                params2.put("wbIdList",wbIdList);
                params2.put("occurrenceTimeList",occurrenceTimeList);
                log.info("params2:{}",params2);
                csvDataList = WeatherMapper.findAllCsvByReq(params2);
            }
            List<CsvData> insertCsv = new ArrayList<>();
            List<Weather> insertWeather = new ArrayList<>();
                    if (csvDataList.size()>0){
                        //有重复的数据不用新增则过滤
                        for (int i=0;i<list.size();i++) {
                            boolean cop =false;
                            for (CsvData csvData2 : csvDataList) {
                                if ((csvData2.getWbId().equals(list.get(i).getWbId())) && (csvData2.getOccurrenceTime().compareTo(list.get(i).getOccurrenceTime()) == 0)) {
                                    //则该条记录是重复的 则过滤
                                    cop=true;
                                    break;
                                }
                            }
                            if (!cop){
                                insertCsv.add(list.get(i));
                                insertWeather.add(list2.get(i));
                            }
                        }
                    }else {
                        for (int i=0;i<list.size();i++){
                            insertCsv.add(list.get(i));
                            insertWeather.add(list2.get(i));
                        }
                    }

            if (insertCsv.size()>0){
                //将数据分批存入数据库
                if (this.saveBatch(insertCsv)){
                    if ( tBusinessService.saveBatch(insertWeather)){
                        list.clear();
                        r.close();
                        return SciaiHttpResponseEntityBuilder.builder().ok("导入成功！").build();
                    }else {
                        list.clear();
                        r.close();
                        return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
                    }
                }else {
                    list.clear();
                    r.close();
                    return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
                }
            }else {
                list.clear();
                r.close();
                return SciaiHttpResponseEntityBuilder.builder().ok("导入的数据全部是重复数据！").build();
            }
        }catch(Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }

    @Override
    public SciaiHttpResponseEntity CSVImport2(String filePath,String date) {

        //接收返回的数据返回给前端
        CsvData csvData =null;
        CsvReader r;
        try{
            // 获取当前日期和时间
            Calendar calendar = Calendar.getInstance();
            // 将日期减去一天
            calendar.add(Calendar.DAY_OF_MONTH, 0);
            // 格式化日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String previousDay = dateFormat.format(calendar.getTime());
            //放文件的位置
//            String cvsFilePath="D:\\"+previousDay+"\\"+filePath;  //本地开发
            log.info("开始file2");
            String cvsFilePath="/opt/project/file/import/"+date+"/"+filePath;  //服务器开发
            log.info("结束file2");
            r = new CsvReader(cvsFilePath,',', Charset.forName("utf-8"));
            //读取表头
            boolean b = r.readHeaders();
            List<CsvData> list = new LinkedList<CsvData>();
            List<Weather> list2 = new LinkedList<Weather>();
            int row =1;
            //先查询天气类型
            //查询天气类型
            Map<String, Object> params = new HashMap<>();
            List<WeatherType> weatherTypes = WeatherMapper.queryWeatherType(params);
            if (weatherTypes.size()==0){
                return SciaiHttpResponseEntityBuilder.builder().error("500", "没有天气类型的基础数据！").build();
            }
            List<String> wbIdList= new ArrayList<>();
            List<String> occurrenceTimeList= new ArrayList<>();
            while(r.readRecord()){
                csvData = new CsvData();
                Weather weather =new Weather();
                weather.setType(2);
                //注意，此处的id,name,school是csv文件里的列名
                String s = r.get("页码");
                String[] strings =  r.getValues();
                int a = Integer.parseInt(strings[0]);
                csvData.setPageNum(a);
                csvData.setWbId(strings[1].substring(1));
                csvData.setWbName(strings[2]);
                weather.setName(strings[2]);
                String dateString = strings[3].replace("/","-");
                int q = dateString.indexOf(" ");
                String str1 =dateString.substring(q);
                List<String> list1 = Arrays.asList(str1.split(":"));
                if (list1.size()==2){
                    dateString=dateString+":00";
                }

//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date1 = DateUtil.parse(dateString, "yyyy-MM-dd HH:mm:ss");
//                Date date = format.parse(dateString);
                csvData.setOccurrenceTime(date1);
                weather.setOccurrenceTime(date1);
                csvData.setContent(strings[4]);
                weather.setDescribeName(strings[4]);
                int a1 = Integer.parseInt(strings[5]);
                csvData.setForwardNum(a1);
                int a2 = Integer.parseInt(strings[6]);
                csvData.setCommentNum(a2);
                int a3 = Integer.parseInt(strings[7]);
                csvData.setLikeNum(a3);
                csvData.setOccurrencePlace(strings[8].equals("")? "":strings[8]);
                csvData.setOccurrenceCity(strings[9].equals("")? "":strings[9]);
                csvData.setOccurrenceProvince(strings[10].equals("")? "":strings[10]);
                weather.setOccurrencePlace(strings[10].equals("")? "":strings[10]);
                csvData.setOccurrenceCountry(strings[11].equals("")? "":strings[11]);
                if (!strings[12].equals("999") && !strings[12].equals("999.0") && !strings[12].equals("999.00")){
                    csvData.setLon(strings[12]);
                    weather.setOccurrencePlace1(strings[12]);
                    csvData.setLat(strings[13]);
                    weather.setOccurrencePlace2(strings[13]);
                    weather.setVideoUuid("");
                    weather.setImagUuid("");
                    weather.setCreateUserId(1);
                    weather.setCreateTime(new Date());
                    boolean f=false; //判断是否在系统的基础数据里 天气类型
                    if (strings[14].equals("")||strings[14].equals("null")||strings[14]==null){
                        return SciaiHttpResponseEntityBuilder.builder().error("500", "第"+row+"行的天气类型不能为空！").build();
                    }else {
                        for (int i=0; i<weatherTypes.size();i++){
                            if (weatherTypes.get(i).getTypeName().equals(strings[14])){
                                csvData.setWeatherType(weatherTypes.get(i).getId());
                                weather.setWeatherType(weatherTypes.get(i).getId());
                                weather.setWeatherTypeName(strings[14]);
                                f=true;
                                break;
                            }
                        }
                    }
                    if (!f){
                        //不在
                        return SciaiHttpResponseEntityBuilder.builder().error("500", "第"+row+"行的天气类型不在基础数据里！").build();
                    }
                    csvData.setCreateTime(new Date());
                    row=row+1;
                    list.add(csvData);
                    wbIdList.add(csvData.getWbId());
                    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String occurrenceTime = dateFormat2.format(csvData.getOccurrenceTime());
                    occurrenceTimeList.add(occurrenceTime);
                    list2.add(weather);
                }
            }
            List<CsvData> csvDataList = new ArrayList<>();
            if (wbIdList.size()>0){
                Map<String, Object> params2 = new HashMap<>();
                params2.put("wbIdList",wbIdList);
                params2.put("occurrenceTimeList",occurrenceTimeList);
                log.info("params2:{}",params2);
                csvDataList = WeatherMapper.findAllCsvByReq(params2);
            }
            List<CsvData> insertCsv = new ArrayList<>();
            List<Weather> insertWeather = new ArrayList<>();
            if (csvDataList.size()>0){
                //有重复的数据不用新增则过滤
                for (int i=0;i<list.size();i++) {
                    boolean cop =false;
                    for (CsvData csvData2 : csvDataList) {
                        if ((csvData2.getWbId().equals(list.get(i).getWbId())) && (csvData2.getOccurrenceTime().compareTo(list.get(i).getOccurrenceTime()) == 0)) {
                            //则该条记录是重复的 则过滤
                            cop=true;
                            break;
                        }
                    }
                    if (!cop){
                        insertCsv.add(list.get(i));
                        insertWeather.add(list2.get(i));
                    }
                }
            }else {
                for (int i=0;i<list.size();i++){
                    insertCsv.add(list.get(i));
                    insertWeather.add(list2.get(i));
                }
            }

            if (insertCsv.size()>0){
                //将数据分批存入数据库
                if (this.saveBatch(insertCsv)){
                    if ( tBusinessService.saveBatch(insertWeather)){
                        list.clear();
                        r.close();
                        return SciaiHttpResponseEntityBuilder.builder().ok("导入成功！").build();
                    }else {
                        list.clear();
                        r.close();
                        return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
                    }
                }else {
                    list.clear();
                    r.close();
                    return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！").build();
                }
            }else {
                list.clear();
                r.close();
                return SciaiHttpResponseEntityBuilder.builder().ok("导入的数据全部是重复数据！").build();
            }
        }catch(Exception e){
            return SciaiHttpResponseEntityBuilder.builder().error("500", "系统出错！" + e.getMessage()).build();
        }
    }
}
